#include "main.h"

static LRESULT listview_message(WPARAM wParam, LPARAM lParam)
{
	switch (((LPNMHDR)lParam)->code)
	{
		case LVN_COLUMNCLICK:
			compare_index = ((NMLISTVIEW *)lParam)->iSubItem;
			sort_danmu(); insert_danmu();
			break;
		case LVN_ITEMACTIVATE:
			open_user_space(((NMITEMACTIVATE *)lParam)->iItem);
			break;
		case NM_CUSTOMDRAW:
		{
			LPNMLVCUSTOMDRAW lplvcd = (LPNMLVCUSTOMDRAW)lParam;
			lplvcd->clrText = get_danmu_colour(
				lplvcd->nmcd.dwItemSpec, lplvcd->iSubItem);
			lplvcd->clrTextBk = 0xffffff - lplvcd->clrText;	
			return CDRF_NOTIFYSUBITEMDRAW;
		}
	}

	return 0;
}

static void resize_(unsigned right, unsigned bottom)
{
	unsigned current_bottom;
#define EDIT_HEIGHT 17
#define MARGIN 5
#define STATIC_HINT_WIDTH 35

#define SET_POS(control, x0, y0, x1, y1) do { \
	set_pos(control, x0, y0, x1, y1); \
	current_bottom = y1; \
} while (0)

	SET_POS(static_edit_hint.handle, 0, MARGIN,
		STATIC_HINT_WIDTH, MARGIN + EDIT_HEIGHT);
	SET_POS(edit.handle, STATIC_HINT_WIDTH, MARGIN,
		right, MARGIN + EDIT_HEIGHT);
	SET_POS(listview.handle, 0, current_bottom,
		right, bottom - 3 * EDIT_HEIGHT);
	SET_POS(static_bottom.handle, 0, bottom - EDIT_HEIGHT - MARGIN,
		right, bottom);
}

static LRESULT CALLBACK listview_wndproc(HWND hwnd,
	UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
		case WM_DESTROY:
			PostQuitMessage(0);
			break;
	
		case WM_SIZE:
			resize();
			break;
			
		case WM_COMMAND:
			if (LOWORD(wParam) == edit.id && HIWORD(wParam) == EN_UPDATE)
				filter();
			break;

		case WM_NOTIFY:
			if (wParam == listview.id)
				return listview_message(wParam, lParam);
			break;
	
		default:
			return DefWindowProc(hwnd, msg, wParam, lParam);
	}
	
	return 0;
}

static void resize_window(void)
{
	RECT rcClient;
	GetWindowRect(main_window, &rcClient);
	MoveWindow(main_window, rcClient.left, rcClient.top,
		rcClient.right + 200, rcClient.bottom, FALSE);
}

extern void listview_init(void)
{
	listview_winapi_wrapper_init();
	resize_window();
	init_columns();
	SetWindowLong(main_window, GWL_WNDPROC, listview_wndproc);
	resize();
}